/**
 * @author HuntBao
 * @context contextmenu for left menu
 */
App.Views.leftMenuContextMenuView = App.Views.contextMenuView.extend({
    id : 'mod-leftmenu-contextmenu',
    
	initialize : function( options ) {
		var self = this;
	    self.$el.html(Mustache.to_html(tpl.contextMenu , self.model.toJSON()));
	    self.$el.bind('click', function(e) {
         	e.stopPropagation();
        });
        $(document).click(function(e){
        	if(e.which === 1 || e.which === 0){
		    	self.hideMenu();
		    }
		});
		self.bindEvent();
		self.appView = options.appView;
		self.appView.$el.append(self.$el);
		self.docList = self.appView.docList;
	},

	contextMenu : function(target, e){
		var self = this;
		if($(target).is('.no-dropdown-menu')) return false;
        self.displayMenu({
            top: e[self.model.get('eventPosY')],
            left: e[self.model.get('eventPosX')]
        }, target);
	},
	
	displayMenu: function(position, selectedItem){
		var self = this,
        menu = self.$el;
        self.selectedItemModel = self.appView.getProjectItemModelById(selectedItem.attr('id'));
        self.$el.hide().find('li').show();
        self.positionMenu(position);
	},
    
    bindEvent: function(){
    	var self = this;
    	self.$el.delegate('li', 'click', function(e){
			var t = $(this);
			if(t.hasClass('editInfoItem')){
				self.editInfoItemHandler(e);
			}else if(t.hasClass('deleteItem')){
				self.deleteItemHandler();
			}else if(t.hasClass('projectRoleItem')){
                self.projectRoleItemHandler();
            }
			self.hideMenu();
			e.stopPropagation();
		});
    },
    
    editInfoItemHandler: function(e){
    	var self = this;
    	App.modalHelper.showNormalModal({
            title: 'editProjectInfo',
            url: App.util.contextPath + '/js/widget/createproject.widget',
            done: function(data, modalBody, okBtn, modal){
                modalBody.empty().html(Mustache.to_html(data, {
                    projectName: App.i18n.get('projectName'),
                    projectNamePH: App.i18n.get('projectNamePH'),
                    projectDescription: App.i18n.get('description'),
                    projectDescriptionPH: App.i18n.get('projectDescriptionPH')
                }));
                var name = modalBody.find('.create-project-name').val(self.selectedItemModel.get('name')),
                description = modalBody.find('.create-project-description').val(self.selectedItemModel.get('description')),
                errorMsg = modal.find('.error-msg'),
                submit = function(){
                    if(okBtn.hasClass('disabled')) return;
                    name.val(name.val());
                    if(name.val() === ''){
                       errorMsg.text(App.i18n.get('projectNamePH'));
                       name.focus();
                       return;
                    }
                    okBtn.addClass('disabled');
                    App.util.showTip(App.i18n.get('isSubmittingInfo'));
                    self.selectedItemModel.set({
                        name: name.val(),
                        description: description.val()
                    });
                    self.selectedItemModel.save(null, {
                    	url: App.util.contextPath + '/project/',
                        success: function(model){
                            App.util.hideTip();
                            modal.modal('hide');
                            okBtn.removeClass('disabled');
                        },
                        error: function(){
                            okBtn.removeClass('disabled');
                        }
                    });
                }
                okBtn.click(submit);
            }
        });
    },
    
    deleteItemHandler: function(e){
    	var self = this;
    	App.modalHelper.showNormalModal({
            title: 'deleteProject',
            url: App.util.contextPath + '/js/widget/createproject.widget',
            done: function(data, modalBody, okBtn, modal){
            	modalBody.html(App.i18n.get('deleteProjectConfirm'));
            	okBtn.addClass('btn-danger');
                var submit = function(){
                    if(okBtn.hasClass('disabled')) return;
                    App.util.showTip(App.i18n.get('isDeletingProject'));
                    self.selectedItemModel.destroy({
                    	url: App.util.contextPath + '/project/' + self.selectedItemModel.get('projectId'),
                        success: function(model, response, options){
                            App.util.actionTip(App.i18n.get('deleteProjectSuccess'));
                            modal.modal('hide');
                            okBtn.removeClass('disabled');
                        },
                        error: function(model, xhr, options){
                            okBtn.removeClass('disabled');
                        },
                        wait: true
                    });
                }
                okBtn.click(submit);
            }
        });
    },
    
    projectRoleItemHandler: function(){
        var self = this;
        App.modalHelper.showNormalModal({
            title: 'projectRoleAndMember',
            modalClass: 'rolemember-project-modal',
            button: {
                ok: 'close',
                cancel: false
            },
            done: function(data, modalBody, okBtn, modal){
            	self.roleModalBody = modalBody;
            	self.roleModal = modal;
            	self.roleModalErrorMsg = modal.find('.error-msg');
                self.appView.RoleCollection.fetch({
                    url: App.util.contextPath + '/role?projectId=' + self.selectedItemModel.get('projectId'),
                    success: function(){
                        self.showRoles();
                    }
                });
                okBtn.click(function(){
                    modal.modal('hide');
                    self.orgModal && self.orgModal.modal('hide');
                });
            }
        });
    },
    
    showRoles: function(){
        var self = this;
        self.roleModalBody.empty().append($('<div>', {
           'class': 'role-lst',
           text: App.i18n.get('projectRoleList')
        }).prepend($('<em>', {
           'class': 'toggle-icon-expand'
        })).append($('<a>', {
           'class': 'create-role',
           text: App.i18n.get('createRole'),
           href: '#'
        }).click(function(e){
           self.addNewRoleRowHandler(e);
           return false;
        })).append($('<a>', {
           'class': 'add-member',
           text: App.i18n.get('addMember'),
           href: '#'
        }).click(function(e){
           self.addNewMemberRowHandler(e);
           return false;
        })).append($('<a>', {
           'class': 'add-org',
           text: App.i18n.get('addOrganization'),
           href: '#'
        }).click(function(e){
           self.addOrganization();
           return false;
        })));
        self.roldModalRoleListWrap = $('<div>', {
            'class': 'role-list-wrap'
        });
        self.roleModalBody.append(self.roldModalRoleListWrap);
        self.appView.RoleCollection.each(function(model){
        	model.set({roleAndMemberModal: true}, {silent: true});
            var view = new App.Views.RoleView({
                model: model
            });
            self.roldModalRoleListWrap.append(view.render().$el);
        });
    },
        
    addNewRoleRowHandler: function(e){
        var self = this;
        var creatingRoleRow = self.roleModalBody.find('.role-row > .editing-row');
        self.removeSelectedItem(e.target);
        if(creatingRoleRow.length > 0){
            creatingRoleRow.find('input').focus();
            creatingRoleRow.parent().addClass('highlight');
            return false;
        }
        var roleModel = new App.Models.itemModel({
            projectId: self.selectedItemModel.get('projectId'),
            editingRow: true,
            editable: true,
            roleAndMemberModal: true
        });
        var view = new App.Views.RoleView({
            model: roleModel
        });
        var el = view.render().$el.addClass('highlight');
        self.roldModalRoleListWrap.append(el);
        el.find('.role-inp').focus();
        return false;
    },
    
    addNewMemberRowHandler: function(e){
        var self = this,
        selectedRole = self.getSelectedRole();
        if(selectedRole === null){
        	var creatingMemberRow = self.roleModalBody.find('.member-row').has('.editing-row');
        	if(creatingMemberRow.length === 0){
                selectedRole = self.getDefaultRole();
            }else{
                creatingMemberRow.find('.member-inp').focus();
                return false;
            }
        }
        if(selectedRole === null) return false;
        var selectedRoleId = self.getSelectedRoleId(selectedRole);
        self.expandOrCollapseRole(selectedRole, true, function(){
            self.addNewMemberRow(e.target, selectedRole, selectedRoleId);
        });
    },
    
    addNewMemberRow: function(target, selectedRole, selectedRoleId){
        var self = this;
        var creatingMemberRow = self.roleModalBody.find('.member-row').has('.editing-row');
        var existInputValue = creatingMemberRow.find('.member-inp').val();
        creatingMemberRow.remove();
    	self.removeSelectedItem(target);
        var memberModel = new App.Models.itemModel({
            projectId: self.selectedItemModel.get('projectId'),
            editingRow: true,
            roleId: selectedRoleId
        });
        var view = new App.Views.MemberView({
            model: memberModel
        });
        var $el = view.render().$el.addClass('highlight');
        $el.appendTo(selectedRole);
        $el.find('.member-inp').focus().val(existInputValue);
        //get suggest list
        App.util.getSuggestMemberList(function(members){
        	var autocompleteSource = [];
        	for(var i = 0, m, label; i < members.length; i++){
                m = members[i];
                label = (m.displayName === m.accountName) ? m.accountName :  (m.displayName + '<' + m.accountName + '>');
                autocompleteSource.push({
                    label: label,
                    value: m.accountName
                });
            }
            if(autocompleteSource.length){
                $el.find('.member-inp').autocomplete({
                    source: autocompleteSource,
                    position: { my : 'left top-1'},
                    minLength: 0
                });
            }
            self.getAccountIdByName = function(name){
                var acccountId = '';
                _.some(members, function(m){
                    if(m.accountName === name){
                        acccountId = m.accountId;
                        return false;
                    }
                    return true;
                });
                return acccountId;
            }
        });
    },
    
    getAccountIdByName: function(name){
        //this function will be override by @addNewMemberRow when suggest list is loaded
        return '';
    },
    
    addOrganization: function(){
    	var self = this;
    	if(!self.addOrgdialog){
        	self.addOrgdialog = $('<div>', {
        	   'class': 'dialog2'
        	}).appendTo(document.body);
    	}
    	App.modalHelper.showNormalModal({
            title: 'addOrganization',
            modalClass: 'rolemember-project-modal addorganization-project-modal',
            button: {
                ok: 'close',
                cancel: false
            },
            modalContainer: self.addOrgdialog,
            style: {
                left: self.roleModal.css('left'),
                top: parseInt(self.roleModal.css('top')) + 3
            },
            backdrop: false,
            done: function(data, modalBody, okBtn, modal){
                self.orgModalBody = modalBody.css('min-height', self.roleModalBody.css('height'));
                self.orgModal = modal;
                self.orgModalErrorMsg = modal.find('.error-msg');
                okBtn.click(function(){
                    modal.modal('hide');
                    self.orgModal.modal('hide');
                });
                self.fetchOrganizations();
            }
        });
    },
    
    fetchMembersByRole: function(projectId, roleId, callback){
        var self = this;
        (new Backbone.Collection).fetch({
            url: App.util.contextPath + '/project/member?projectId='+ projectId+'&roleId='+ roleId,
            success: function(collection, options){
            	callback && callback(collection.at(0).toJSON().items);
            }
        });
    },
    
    expandOrCollapseRole: function(roleEle, expand, callback){
        var self = this;
        if(roleEle === null){
            callback && callback();
            return false;
        }
        var roleId = self.getSelectedRoleId(roleEle),
        roleModel = self.appView.RoleCollection.get(roleId);
        if(roleModel.set('expandToggleIcon', expand))
        if(roleModel.get('memberDataLoaded')){
           //todo
           roleEle.find('.member-row')[expand ? 'show' : 'hide']();
           callback && callback();
        }else{
            roleEle.addClass('loading-data');
            //get role's members
            self.fetchMembersByRole(roleModel.get('projectId'), roleModel.get('id'), function(datas){
                roleModel.set({memberDataLoaded: true}, {silent: true});
                roleEle.removeClass('loading-data');
                self.addMembersByRawData(datas, roleEle, true);
                callback && callback();
            });
        }
    },
    
    fetchOrganizations: function(){
        var self = this;
        var selectedRoleId = self.getSelectedRoleId();
        if(selectedRoleId === ''){
            selectedRoleId = self.getDefaultRoleId();
        }
        //get my organizations
        (new Backbone.Collection).fetch({
            url: App.util.contextPath + '/project/org?projectId='+ self.selectedItemModel.get('projectId') + '&roleId=' + selectedRoleId,
            success: function(collection, options){
                var data = collection.at(0).toJSON().items;
                self.orgModalBody.empty();
                if(data.length === 0){
                    //has no organization yet
                    self.orgModalBody.text(App.i18n.get('NoOrganizationTip'));
                    $('<a>', {
                        href: App.util.accountURL + '/info#organization',
                        target: '_blank',
                        text: App.i18n.get('CreateNewOrganization'),
                        'class': 'create-new-org'
                    }).appendTo(self.orgModalBody);
                }else{
                    self.addMembersByRawData(data, self.orgModalBody, false);
                }
            }
        });
    },
    
    addMembersByRawData: function(members, container, flattenMember){
        var self = this;
        _.each(members, function(member){
            if(flattenMember && member.org && member.memberViews.length > 0){
        		member = self.flattenOrgMemberData(member);
            }
            var memberModel = new App.Models.itemModel(member);
            var view = new App.Views.MemberView({
                model: memberModel
            });
            self.appView.MemberCollection.add(memberModel);
            var $el = view.render().$el;
            $el.appendTo(container);
            if(member.org){
                $el.addClass('member-org-row');
                if(memberModel.get('status') === 1){
                    self.changeSubOrgStatus(member.memberViews);
                }
            }
            if(member.org && member.memberViews.length > 0){
                $el.find('.toggle-icon').addClass('toggle-icon-expand');
                //currently, only flatten the first level, so here @flattenMember is false
                self.addMembersByRawData(member.memberViews, $el);
            }
        });
    },
    
    flattenOrgMemberData: function(orgMemberData){
        var self = this;
        var flattenPath = function(data, path){
            if(data.nameNode){
                data.name = (path ? path : '') + data.name;
                return data;
            }else{
                return flattenPath(data.memberViews[0], data.name + '-');
            }
        }
        var flattenedData = flattenPath(orgMemberData);
        return flattenedData;
    },
    
    changeSubOrgStatus: function(members){
        var self = this;
        var changeStatus = function(ms){
            _.each(ms, function(m){
            	//change all sub org's status to 'accept', the value is 1
                m.status = 1;
                if(m.org && m.memberViews.length > 0){
                    changeStatus(m.memberViews);
                }
            });
        }
        changeStatus(members);
    },
    
    updateAddOrganizationModal: function(){
        var self = this;
        if(self.orgModal && self.orgModal.data('modal').isShown){
            self.fetchOrganizations();
        }
    },
    
    removeSelectedItem: function(target){
        var self = this;
        $(target).closest('.modal-wrap').find('.highlight').removeClass('highlight deleting-row');
    },
    
    getSelectedRole: function(){
        var self = this,
        selectedRole = self.roleModalBody.find('.role-row.highlight');
        if(selectedRole.length === 0 || selectedRole.find('.editing-row').length > 0){
            //no selected role
            return null;
        }
        return selectedRole;
    },
    
    getSelectedRoleId: function(selectedRole){
    	var self = this,
        selectedRole = selectedRole || self.getSelectedRole();
        if(selectedRole && selectedRole.length > 0){
            return App.util.removePrefixOfId(selectedRole.attr('id'));
        }else{
            return '';
        }
    },
    
    getDefaultRole: function(){
        var self = this,
        defaultRole = self.roleModalBody.find('.default-role');
        return defaultRole;
    },
    
    getDefaultRoleId: function(){
        var self = this,
        defaultRole = self.getDefaultRole();
        return App.util.removePrefixOfId(defaultRole.attr('id'));
    }
});
